package com.wanlian.router.net.netty;

import com.smart.android.utils.Logger;
import com.wanlian.router.net.netty.core.IMClientHandler;
import com.wanlian.router.net.netty2.handler.DeviceClientHandler;
import com.wanlian.router.net.netty2.model.Address;
import com.wanlian.router.net.netty2.msg.BaseMsg;
import com.wanlian.router.net.netty2.msg.PeerMsg;
import com.wanlian.router.net.netty2.msg.PeerMsgDecoder;
import com.wanlian.router.net.netty2.msg.PeerMsgEncoder;
import com.wanlian.router.net.netty2.msg.RegisterMsg;
import com.wanlian.router.utils.JsonStringUtil;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyClient implements Runnable {

    private final BlockingQueue<PeerMsg> requests = new LinkedBlockingQueue<>();

    private IMClientHandler clientHandler;
    /**
     * 是否继续进行运行
     */
    private boolean run = true;

    public void addMsg(PeerMsg msg) {
        requests.add(msg);
    }

    public void run() {
        //远程IP
//        String host = "47.75.195.106";
        String host = "47.75.195.106";
        //端口号
        int port = 9001;
        //工作线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.handler(new LoggingHandler(LogLevel.INFO));
            b.handler(new ChannelInitializer<SocketChannel>() {
                public void initChannel(SocketChannel ch) {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast(new PeerMsgDecoder());
                    pipe.addLast(new PeerMsgEncoder());
                    pipe.addLast(new DeviceClientHandler());
//                    pipe.addLast(new ClientHeartbeatHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // (5)

            if (f.isSuccess()) {
                Logger.i("connect success");

                SocketChannel socketChannel = (SocketChannel) f.channel();

                BaseMsg registerMsg = new RegisterMsg();
                Address tAddress = new Address();
                tAddress.setPublickey("a1");

                registerMsg.setClientId("a1");
                registerMsg.setTagClientId("a1");
                registerMsg.setContent(JsonStringUtil.writeValueAsString(tAddress));
                PeerMsg peerMsg = new PeerMsg(registerMsg);
                socketChannel.writeAndFlush(peerMsg);

                while (run) {
                    if (requests.size() > 0) {
                        peerMsg = requests.take();
                        socketChannel.writeAndFlush(peerMsg);
                    }else {
                        Thread.sleep(1000);
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            run = false;
        } finally {
            //优雅的关闭工作线程
            workerGroup.shutdownGracefully();
        }
    }

}
